package com.chcit.mobile.mvp.common.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.LinearLayoutCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import com.chcit.custom.view.loader.LoaderStyle;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.mobile.BuildConfig;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.SupportToolbarFragement;
import com.chcit.mobile.app.utils.BarcodeUtil;
import com.chcit.mobile.app.utils.DiaplayUtils;
import com.chcit.mobile.app.utils.SharedPreUtils;
import com.chcit.mobile.common.DataKeys;
import com.chcit.mobile.di.component.DaggerLoginComponent;
import com.chcit.mobile.di.module.LoginModule;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.helper.UpdateAppHttpUtil;
import com.chcit.mobile.mvp.common.contract.LoginContract;
import com.chcit.mobile.mvp.common.presenter.LoginFragmentPresenter;
import com.chcit.mobile.mvp.home.HomeActivity;
import com.jess.arms.base.app.ConfigKeys;
import com.jess.arms.base.app.Quick;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.vector.update_app.listener.IUpdateDialogFragmentListener;
import com.xuexiang.xui.widget.toast.XToast;

import org.json.JSONObject;
import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class LoginFragment extends SupportToolbarFragement<LoginFragmentPresenter> implements LoginContract.FragmentView {

    public static LoginFragment newInstance() {
        LoginFragment fragment = new LoginFragment();
        return fragment;
    }
    @BindView(R.id.login_picture)
    ImageView loginPicture;
    @BindView(R.id.account)
    EditText account;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.ll_user_info)
    LinearLayoutCompat llUserInfo;
    @BindView(R.id.login)
    Button login;
    @BindView(R.id.root_content)
    LinearLayoutCompat llContent;
    @BindView(R.id.ll_root)
    LinearLayoutCompat llLoginRoot;

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerLoginComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .loginModule(new LoginModule(this))
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_login, container, false);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        //((ImageView)mCommonToolbar.getViewByTag(1)).setImageResource(R.mipmap.exit_32);
        mCommonToolbar.getLeftMenuView(0).setOnClickListener(v->{
            BarcodeUtil.getInstance().destroyAidBroad();
            ArmsUtils.exitApp();
        });
        mCommonToolbar.getRightMenuView(0).setOnClickListener(v->{
            startWithPop(ServerFragment.newInstance());
        });
        keepLoginBtnNotOver(llLoginRoot, llContent);

        //触摸外部，键盘消失
        llLoginRoot.setOnTouchListener((v, event) -> {
            hideSoftInput();
            return false;
        });

        //mCommonToolbar.addRightIcon(4,R.drawable.ic_service,null);

    }
    /**
     * 保持登录按钮始终不会被覆盖
     *
     * @param root
     * @param subView
     */
    private void keepLoginBtnNotOver(final View root, final View subView) {
        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                // 获取root在窗体的可视区域
                root.getWindowVisibleDisplayFrame(rect);
                // 获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInvisibleHeight = root.getRootView().getHeight() - rect.bottom;
                // 若不可视区域高度大于200，则键盘显示,其实相当于键盘的高度
                if (rootInvisibleHeight > 200) {
                    // 显示键盘时
                    int srollHeight =   rootInvisibleHeight - (root.getHeight()-subView.getBottom()) - DiaplayUtils.getNavigationBarHeight(root.getContext());
                    if (srollHeight > 0) {//当键盘高度覆盖按钮时
                        root.scrollTo(0, srollHeight);
                    }
                } else {
                    // 隐藏键盘时
                    root.scrollTo(0, 0);
                }
            }
        });
    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        account.addTextChangedListener(textWatcher);
        password.addTextChangedListener(textWatcher);
        account.setText(SharedPreUtils.getInstance().getString(DataKeys.USERNAME.name(),""));
        String baseUrl = SharedPreUtils.getInstance().getBaseUrl();
        //检测更新
        QuickLoader.showLoading(mContext,LoaderStyle.BallSpinFadeLoaderIndicator.name(),true);
        new UpdateAppManager
                .Builder()
                //当前Activity
                .setActivity(getActivity())
                //更新地址
                .setUpdateUrl(baseUrl+ BuildConfig.DOWN_URL)
                //实现httpManager接口的对象
                .showIgnoreVersion()
                .setHttpManager(new UpdateAppHttpUtil())
                .setUpdateDialogFragmentListener(new IUpdateDialogFragmentListener() {
                    @Override
                    public void onUpdateNotifyDialogCancel(UpdateAppBean updateApp) {

                    }
                })

                .build()
                .checkNewApp(new UpdateCallback(){
                    protected UpdateAppBean parseJson(String json) {
                        UpdateAppBean updateAppBean = new UpdateAppBean();
                        try {
                            JSONObject jsonObject = new JSONObject(json);
                            updateAppBean.setUpdate(jsonObject.optString("update"))
                                    //存放json，方便自定义解析
                                    .setOriginRes(json)
                                    .setNewVersion(jsonObject.optString("new_version"))
                                    .setApkFileUrl(baseUrl+jsonObject.optString("apk_file_url"))
                                    .setTargetSize(jsonObject.optString("target_size"))
                                    .setUpdateLog(jsonObject.optString("update_log"))
                                    .setConstraint(jsonObject.optBoolean("constraint"))
                                    .setNewMd5(jsonObject.optString("new_md5"));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return updateAppBean;
                    }

                    @Override
                    protected void onAfter() {
                        QuickLoader.stopLoading();
                    }
                })
        //.update()
        ;
    }


    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        pop();
    }

    @Override
    public void toHomeActivity() {

        HttpClientHelper.showWareSelect(mContext, (dialog, itemView, which, text) -> {

            Quick.withConfigure(ConfigKeys.WAREHOUSE,which);
            startActivity(new Intent(mContext,HomeActivity.class));
            if( getActivity()!= null){
                getActivity().finish();
            }
            return true;
        });


    }

    @OnClick(R.id.login)
    void onClickSignIn() {
        String userName = account.getText().toString();
        String passWord = password.getText().toString();
        mPresenter.login(userName,passWord);
    }

    private int mEditTextHaveInputCount;
    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            /** EditText内容改变之后 内容为空时 个数减一 按钮改为不可以的背景*/
            if (TextUtils.isEmpty(s)) {
                mEditTextHaveInputCount--;
                login.setEnabled(false);
            }
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            /** EditText最初内容为空 改变EditText内容时 个数加一*/
            if (TextUtils.isEmpty(s)) {

                mEditTextHaveInputCount++;
                /** 判断个数是否到达要求*/
                /* EditText总个数
                 */ /**
                 * EditText总个数
                 */int EDITTEXT_AMOUNT = 2;
                if (mEditTextHaveInputCount == EDITTEXT_AMOUNT) {
                    login.setEnabled(true);
                }
            }

        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
            QuickLoader.stopLoading();
        }
    }
}
